package com.inteligencia.stage.services.mail;

import com.inteligencia.stage.services.util.exception.PlugableServiceException;

import org.springframework.beans.factory.xml.XmlBeanDefinitionReader;
import org.springframework.context.support.GenericApplicationContext;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;

public class MailServiceFactory {

    protected static Resource resource;
    protected static GenericApplicationContext ctx;
    private MailService mailService;

    static {
        resource = new ClassPathResource("mail-service-config.xml");
        load();
    }

    protected static void load() {
        try {
            ctx = new GenericApplicationContext();
            XmlBeanDefinitionReader xmlReader = new XmlBeanDefinitionReader(ctx);
            xmlReader.loadBeanDefinitions(resource);
        } catch (Exception e) {
            e.printStackTrace();
            throw new PlugableServiceException(e);
        }
    }

    public static MailService create(Object initParam) {

        MailService mailService = null;

        try {
            MailServiceFactory mailServiceFactory = (MailServiceFactory) ctx.getBean("mailServiceFactory");
            mailService = mailServiceFactory.getMailService();

            if (mailService.isInitialized()) {
                mailService.initialize(initParam);
            }
        } catch (Exception e) {
            throw new PlugableServiceException(e);
        }
        return mailService;
    }

    public MailService getMailService() {
        return mailService;
    }

    public void setMailService(MailService mailService) {
        this.mailService = mailService;
    }
}